# Server serve the game

$LOAD_PATH << "D:/ruby/mylib"
require "web_socket"
require "thread"

Thread.abort_on_exception = true

if ARGV.size != 2
  $stderr.puts("Usage: ruby sample/chat_server.rb ACCEPTED_DOMAIN PORT")
  exit(1)
end

server = WebSocketServer.new(
  :accepted_domains => [ARGV[0]],
  :port => ARGV[1].to_i())
puts("Server is running at port %d" % server.port)

connections = []
pos = []

server.run() do |ws|
  begin
    puts("Connection accepted")
	ws.handshake()
    que = Queue.new()
    connections.push(que)
	idx = connections.index que
	ws.send("init:"+idx.to_s) #send id
	
    thread = Thread.new() do
      while true
        message = que.pop()
        ws.send(message)
        puts("Sent: #{message}")
      end
    end
   
	if(connections.length == 2) then
		for conn in connections
			conn.push("start:10")
		end
	end
	
    while data = ws.receive()
      puts("Received: #{data} from #{idx}")
      connections[1-idx].push( "bar:#{data}" )
    end
    
  ensure
    connections.delete(que)
    thread.terminate() if thread
    puts("Connection closed")
  end
end
